﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Models;
using FluentValidation;
using Micrhard.FMCG.Server.Msg;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core;
using FluentValidation.Results;

namespace Micrhard.FMCG.Server.Validator
{
    public class KAModelValidator : AbstractValidator<KAModel>
    {
        public KAModelValidator()
        {
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.Name).NotEmpty().WithMessage(KAMsg.NeedName).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Name).Length(1, 50).WithMessage(KAMsg.NameMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Address).Length(0, 200).WithMessage(KAMsg.AddressMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Contractor).Length(0, 50).WithMessage(KAMsg.ContractorMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Cellphone).Length(0, 50).WithMessage(KAMsg.CellphoneMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.CustomerCode).NotEmpty().WithMessage(KAMsg.NeedCustomerCode).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.CustomerCode).Length(1, 50).WithMessage(KAMsg.MaxCustomerCodeLength).When(r => r.KAID == Guid.Empty);

                Custom(u =>
                {
                    IKA ka = IoC.Resolve<IKA>();
                    if (ka.IsDuplicate(u))
                    {
                        return new ValidationFailure("Name", KAMsg.DuplicateName);
                    }
                    if (ka.IsCustomeCodeDuplicate(u))
                    {
                        return new ValidationFailure("CustomerCode", KAMsg.DuplicateCustomerCode);
                    }
                    return null;
                });
            });

            RuleSet("Update", () =>
            {
                RuleFor(u => u.Address).Length(0, 200).WithMessage(KAMsg.AddressMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Contractor).Length(0, 50).WithMessage(KAMsg.ContractorMaxLength).When(r => r.KAID == Guid.Empty);
                RuleFor(u => u.Cellphone).Length(0, 50).WithMessage(KAMsg.CellphoneMaxLength).When(r => r.KAID == Guid.Empty);
            });
        }
    }
}
